<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :showFooter="!isLook"
    :title="isLook ? '查看角色' : getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :disabled="isLook">
      <template #menu="{ model, field }">
        <BasicTree
          :disabled="isLook"
          v-model:value="model[field]"
          v-model:expandedKeys="expandedKeys"
          :treeData="treeData"
          defaultExpandAll
          :fieldNames="{ title: 'title', key: 'kid' }"
          checkable
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';

  import { addAuthRoleItem, editAuthRoleItem, getAccountAuthList } from '@/api/system/account';
  import { AccountAuthListItem } from '@/api/system/model/accountModel';
  import { isArray } from '@/utils/is';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '@/hooks/web/useMessage';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      const expandedKeys = ref<string[]>([]);
      const aRoleList = ref([]);
      const aRoleSelect = ref([]);
      const { createMessage } = useMessage();
      const isLook = ref(false);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        isLook.value = !!data?.record?.isLook;
        resetFields();
        expandedKeys.value = ['99999'];
        aRoleSelect.value = [];
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        let authValue = {
          id: data.record?.id || -1,
        };
        if (authValue.id == -1) delete authValue.id;
        let authData = (await getAccountAuthList(authValue)) as any as AccountAuthListItem;
        console.log(authData, 'authData11111111111');
        aRoleList.value = authData.routes as [];
        let tempMenuList = cloneDeep(authData.routes);
        fnFindParentCheck(tempMenuList, true);
        treeData.value = [
          {
            title: '全部页面',
            kid: '99999',
            icon: 'ion:aperture-outline',
            children: fnRoleRecursion(tempMenuList),
          },
        ] as any as TreeItem[];
        // console.log(fnRoleRecursion(tempMenuList), 'fnRoleRecursion(tempMenuList)55566');
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
            ...{ menu: unref(aRoleSelect) },
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          aRoleSelect.value = values.menu;
          let tempOpj = cloneDeep(values);
          tempOpj.auth = fnRoleRecursion(cloneDeep(unref(aRoleList)), true);
          delete tempOpj.menu;
          fnFindParentCheck(tempOpj.auth);
          if (!unref(isUpdate)) delete tempOpj.id;
          tempOpj.id = parseInt(tempOpj.id);
          const codeData = unref(isUpdate)
            ? await editAuthRoleItem(tempOpj, { AccessId: 7 })
            : await addAuthRoleItem(tempOpj, { AccessId: 7 });
          if (codeData === 0) setDrawerProps({ confirmLoading: false });
          createMessage.success('保存成功', 0.5, () => {
            closeDrawer();
          });
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      function fnRoleRecursion(data, isEdit = false) {
        let tempData: any;
        if (isArray(data)) {
          let tempList: any[] = [];
          data.forEach((v) => {
            // v.parent_id_menu = v.parent_id;
            v.kid = v.parent_id + '__' + v.id;
            if (!isEdit && v.model) {
              let tempList: any = cloneDeep(unref(aRoleSelect));
              tempList.push(v.kid);
              aRoleSelect.value = tempList;
            }
            if (!v.title) v.title = v.name;
            // delete v.parent_id;
            if (isEdit) {
              v.model = unref(aRoleSelect).indexOf(v.kid) >= 0;
            }
            if (v.children && isArray(v.children) && v.children.length) {
              if (isEdit) {
                v.indeterminate = unref(aRoleSelect).indexOf(v.kid) >= 0;
              }
              v.children = fnRoleRecursion(v.children, isEdit);
            } else {
              v = fnRoleRecursion(v, isEdit);
            }
            if (v.level == 1) {
              let tempKeys = cloneDeep(unref(expandedKeys));
              tempKeys.indexOf(v.kid) < 0 && tempKeys.push(v.kid);
              expandedKeys.value = tempKeys;
            }
            tempList.push(v);
          });
          tempData = tempList;
        } else {
          tempData = data;
        }
        return tempData;
      }

      function fnFindParentCheck(menuData, isOver = false) {
        let isCheck = isOver;
        if (isArray(menuData)) {
          menuData.forEach((v) => {
            if (v.children) {
              v.model = fnFindParentCheck(v.children, isOver);
            }
            if (isOver) {
              if (!v.model) isCheck = false;
            } else {
              if (v.model) isCheck = true;
            }
          });
        }
        return isCheck;
      }

      // function fnFindCheck(childData) {
      //   let isCheck = false;
      //   if (isArray(childData)) {
      //     childData.forEach((v) => {
      //       if (v.children) {
      //         v.indeterminate = fnFindCheck(v.children);
      //       }
      //       if (v.indeterminate) isCheck = true;
      //     });
      //   }
      //   return isCheck;
      // }

      return {
        expandedKeys,
        registerDrawer,
        isLook,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
      };
    },
  });
</script>
